﻿#include <learn/topo/topo_builder.h>
#include <learn/topo/topo_coedge.h>
#include <learn/topo/topo_face.h>
#include <learn/topo/topo_wire.h>

using namespace xi;
using namespace xi::topo;

Topo_Wire::Topo_Wire() : Topo_Shape(), m_coedge(nullptr), m_next(nullptr), m_loop(Topo_Loop::Boundary)
{
}

Topo_Wire::~Topo_Wire()
{
    // 如果 wire 还有下一条 loop，应该报错，不允许删除顶层的 wire
    ASSERT_INFO(m_next == nullptr, "Topo_Wire should not be deleted while it has a next loop");

    Topo_Builder builder;
    switch (m_loop)
    {
    // 内部 loop 要移除所有 coedge 对
    case Topo_Loop::Interior: {
        auto co = m_coedge;
        auto co2 = co;
        while (co != nullptr)
        {
            co = co->next();
            co2->wire() = nullptr;
            builder.remove_coedge(co2);
            co2 = co;

            if (co == m_coedge)
                break;
        }
        break;
    }
        // 边界 loop 移除 coedge 中的 loop 标记，以及前后连接
    case Topo_Loop::Boundary: {
        auto co = m_coedge;
        auto co2 = co;
        while (co != nullptr)
        {
            co = co->next();
            co2->wire() = nullptr;
            co2->prev() = nullptr;
            co2->next() = nullptr;
            co2 = co;

            if (co == m_coedge)
                break;
        }
        break;
    }
    default:
        break;
    }

    // 如果 wire 是 face 上的唯一 wire，应该删除 face
    if (m_face != nullptr && m_face->wire() == this)
    {
        m_face->wire() = nullptr;
        builder.remove_face(m_face);
        m_face = nullptr;
    }
}

Topo_Face *&Topo_Wire::face()
{
    return m_face;
}

Topo_Coedge *&Topo_Wire::coedge()
{
    return m_coedge;
}

Topo_Wire *&Topo_Wire::next()
{
    return m_next;
}

Topo_Loop Topo_Wire::loop() const
{
    return m_loop;
}